data "terraform_remote_state"
別のTerraform Moduleに保存されているtfstateをTerraformのremote backendを介して読み出すことができる
https://developer.hashicorp.com/terraform/language/state/remote-state-data
GPT-4o.icon
🔍 terraform_remote_state とは?
別の Terraform プロジェクト(構成)の output variable (Terraform)を参照できる仕組み です。
例
Terraform の構成が2つあるとします:
渡す側(書き出し)
受け取る側(読み込み)
🧱 渡す側(例)
まず、vpc-prod という Workspace または Project で VPC を定義している Terraform 構成があります。
code:hcl(rb)
resource "aws_vpc" "main" {
# VPC 作成など
}
resource "aws_subnet" "main" {
vpc_id = aws_vpc.main.id
}
output "subnet_id" {
value = aws_subnet.main.id
}
この構成が subnet_id を出力しており、これを他の構成から利用したい。
受け取る側
data "terraform_remote_state"を使う
code:hcl(rb)
data "terraform_remote_state" "vpc" {
backend = "remote"
config = {
organization = "hashicorp"
workspaces = {
name = "vpc-prod" # ← 上の構成の Workspace 名
}
}
}
resource "aws_instance" "foo" {
subnet_id = data.terraform_remote_state.vpc.outputs.subnet_id
}
この構成は、先ほどの VPC 構成の subnet_id output を参照しています。
このコードは EC2 インスタンスを作成する別の構成であり、vpc-prod の output を使っています。
🔒 セキュリティに注意
outputs しか使えないように見えるが、
実際には state 全体にアクセス可能な権限が必要なので、
state に含まれる機密情報が漏れるリスクがあります。
✅ HCP Terraform or Terraform Enterprise を使っている場合は、より安全な tfe_outputs データソースの使用を推奨しています。
---
🛠 利用方法(例)
Remote Backend を使う場合
code:hcl(rb)
data "terraform_remote_state" "vpc" {
backend = "remote"
config = {
organization = "hashicorp"
workspaces = { name = "vpc-prod" }
}
}
Local Backend を使う場合
code:hcl(rb)
data "terraform_remote_state" "vpc" {
backend = "local"
config = {
path = "../vpc/terraform.tfstate"
}
}
⚠ 注意点
出力は「ルートモジュールのみ」
ネストしたモジュール(module.xxx)の output を使いたい場合は、ルートに明示的に出力を passthrough する必要があります。
code:hcl
module "app" {
source = "..."
}
output "app_value" {
value = module.app.example
}
🧩 より良い代替手段(明示的な共有)
terraform_remote_state は便利ですが、\*\*「隠れた依存」や「過剰な権限」\*\*が問題になります。
代替手段として、以下のように 外部ストアに output を publish して別構成が参照するのがベターです。
table:table
システム 書き込み(リソース) 読み込み(データソース)
----------------------- ----------------------- -----------------------
AWS SSM Parameter Store aws_ssm_parameter aws_ssm_parameter
S3 aws_s3_object aws_s3_object
Consul consul_key_prefix consul_key_prefix
Kubernetes kubernetes_config_map kubernetes_config_map
これにより、以下の利点があります:
アクセス制御を柔軟に設定できる
他のシステム(Kubernetes, Nomad, Config Mgmtなど)からも利用できる
依存が Terraform 内に閉じない